import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '@/views/home.vue';
import store from '../store/index';
import axios from 'axios';
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      areadyLoginRedirect: true
    },
    component: () => import(/* webpackChunkName: "login" */ '../views/login.vue')
  },
  {
    path: '/signup',
    name: 'signup',
    meta: {
      areadyLoginRedirect: true
    },
    component: () => import(/* webpackChunkName: "signup" */ '../views/signup.vue')
  },
  {
    path: '/create',
    name: 'create',
    meta: {
      requiredLogin: true
    },
    component: () => import(/* webpackChunkName: "create" */ '../views/createPost.vue')
  },
  {
    path: '/column/:cid',
    name: 'column',
    component: () => import(/* webpackChunkName: "column" */ '../views/ColumnDetail.vue')
  },
  {
    path: '/article/:id',
    name: 'article',
    component: () => import(/* webpackChunkName: "article" */ '../views/ArticleDetail.vue')
  },
  {
    path: '/articlelist',
    name: 'articlelist',
    component: () => import(/* webpackChunkName: "articlelist" */ '../views/ArticleList.vue')
  }
];
// console.log(process.env, 'process.envcs');
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  if (store.state.user.isLogin) {
    if (to.meta.areadyLoginRedirect) {
      next('/');
    } else {
      next();
    }
  } else {
    if (store.state.token) {
      axios.defaults.headers.common.Authorization = 'Bearer ' + store.state.token;
      store
        .dispatch('fetchCurrentUser')
        .then(() => {
          if (to.meta.areadyLoginRedirect) {
            next('/');
          } else {
            next();
          }
        })
        .catch(e => {
          store.commit('logout');
          next('login');
        });
    } else {
      if (to.meta.requiredLogin) {
        next('login');
      } else {
        next();
      }
    }
  }
});

export default router;
